import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:magic_car/common/nodata.dart';
import 'package:magic_car/inspect/InspectorManager.dart';
import 'package:magic_car/inspect/Manegerinspector.dart';
import 'package:magic_car/inspect/inspectinfo.dart';
import 'package:magic_car/site/siteinfo.dart';
import 'package:magic_car/user/anserdetail.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';

class PartInspectorPage extends StatefulWidget {
  PartInspectorPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<PartInspectorPage> {
  GlobalKey _myKey = new GlobalKey();
  List formList;
  ScrollController _controller = new ScrollController();
  int page = 1;
  bool end = false;
  String keyword = "";
  List sites = [];
  bool hasload = false;
  List items = [
    {
      'title': '线上考试',
      'select': false,
      'value': '',
      'code': 'online',
      'option': '全部,合格,不合格',
      'type': 1,
      'value_des': ''
    },
    {
      'title': '线下考试',
      'select': false,
      'value': '',
      'code': 'underline',
      'option': '全部,合格,不合格',
      'type': 1,
      'value_des': ''
    },
    {
      'title': '正式检测师',
      'select': false,
      'value': '',
      'code': 'inspector',
      'option': '全部,是,否',
      'type': 1,
      'value_des': ''
    },
    {
      'title': '站点',
      'select': false,
      'value': '',
      'code': 'site',
      'type': 2,
      'value_des': ''
    },
  ];

  initState() {
    super.initState();
    _controller.addListener(() {
      if (_controller.position.pixels == _controller.position.maxScrollExtent) {
        print('滑动到了最底部');
        if(end){
          Toast.show("无更多数据", context);
        }else
        loadData();
      }
    });

    formList = [];
    loadData();
    loadsiteData();
  }

  //加载站点数据
  loadsiteData() async {
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["pid"] = pref.getString('uid');

    print(map);

    HttpHelper.post(HttpHelper.API_GetSites, (data) async {
      if (data != null) {
        print(data);
        setState(() {
          sites = data['info'];
        });
      }
    }, params: map);
  }

  //加载数据
  loadData() async {
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["id"] = pref.getString('uid');
    map["page"] = page.toString();
    map["keyword"] = keyword;
    map["type"] = "1";
    var role = pref.getString('role');
    if (role == '1') {
      map['type'] = '2';
    }
    items.forEach((element) {
      var code = element['code'];
      map[code] = element['value'];
    });
    print(map);

    if (page == 1) {
      formList = [];
    }

    HttpHelper.post(HttpHelper.API_MyInspector, (data) async {
      if (data != null) {
        print(data);
        print(data["info"].length.toString());
        if (data["info"].length == 0) {
          Toast.show('暂无更多数据', context);
        } else {
          setState(() {
            hasload = true;
          });

          formList.addAll(data["info"]);
          setState(() {
            formList = formList;
          });

          if (data["code"].toString() == "1") {
            if (data["info"].length < 10) {
              setState(() {
                end = true;
              });
            }else{
              page ++;
            }
            // if (page > 1) {
            //   List add = data["info"];
            //   formList.addAll(add);
            //   setState(() {
            //     formList = formList;
            //   });
            // } else {
            //   setState(() {
            //     formList = data["info"];
            //     page = page + 1;
            //   });
            // }
          }
        }
      }
    }, params: map);
  }

  Widget buildImgs(item) {
    List<Widget> tiles = [];

    Widget content;

    List items = item["image_url"];

    for (var i = 0; i < items.length; i++) {
      //List temp1 = items[i] as List;
      tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(5, 0, 0, 10),
        child: GestureDetector(
            onTap: () {},
            child: Image.network(items[i], width: 100, height: 100)),
      ));
    }
    content = new Wrap(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    Widget content;
    if (formList.length > 0) {
      for (var item in formList) {
        tiles.add(Padding(
            padding: new EdgeInsets.fromLTRB(15, 10, 15, 0),
            child: Container(
              decoration: new BoxDecoration(
                color: Colors.white,
                borderRadius: new BorderRadius.circular(5),
              ),
              child: new GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new ShenhePage(item["id"].toString());
                  })).then((param) {
                    page = 1;
                    loadData();
                  });

                  // Navigator.of(context)
                  //     .push(new MaterialPageRoute(builder: (_) {
                  //   return new ShenhePage(item["id"].toString());
                  //   // return new ManInspectorInfoPage(item["id"].toString());
                  // }));
                },
                child: new Container(
                    child: new Row(children: <Widget>[
                  Padding(
                      padding: new EdgeInsets.fromLTRB(20, 20, 20, 20),
                      child: new Container(
                          decoration: new BoxDecoration(
                            border: new Border.all(
                                color: Color.fromRGBO(27, 182, 251, 1),
                                width: 0.5), // 边色与边宽度
                            color: Color(0xFF9E9E9E), // 底色
                            //        borderRadius: new BorderRadius.circular((20.0)), // 圆角度
                            borderRadius:
                                new BorderRadius.circular(25), // 也可控件一边圆角大小
                          ),
                          height: 50,
                          width: 50,
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(25),
                            child:item['avatar']==""?Image.asset("resource/images/user/user6.png"):CachedNetworkImage(imageUrl: item['avatar'],fit: BoxFit.cover,)
                            // child: FadeInImage.assetNetwork(
                            //   placeholder: "resource/images/user/user6.png",
                            //   image: item['avatar'],
                            //   fit: BoxFit.cover,
                            // ),
                          ))),
                  // child: item['avatar'] != ""
                  //     ? Image.network(
                  //         item['avatar'],

                  //       )
                  //     : Image.asset('resource/images/user/user6.png'))),
                  Expanded(
                    child: new Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Padding(
                            padding: new EdgeInsets.fromLTRB(0, 5, 20, 5),
                            child: Text(item['name'])),
                        Padding(
                            padding: new EdgeInsets.fromLTRB(0, 0, 20, 5),
                            child: Text(
                             "电话：${ item['mobile']}",
                              style: TextStyle(
                                  fontSize: 12,
                                  color: Color.fromRGBO(120, 120, 120, 1)),
                            )),
                        Text(
                          item['provinceName'] == null
                              ? '暂无区域'
                              : item['provinceName'] +
                                  item['cityName'] +
                                  item['areaName'],
                          style: TextStyle(
                              fontSize: 12,
                              color: Color.fromRGBO(120, 120, 120, 1)),
                        ),
                        Padding(
                            padding: new EdgeInsets.fromLTRB(0, 5, 20, 0),
                            child: Text(
                              '站点：' + item['site_name'],
                              style: TextStyle(
                                  fontSize: 12,
                                  color: Color.fromRGBO(120, 120, 120, 1)),
                            )),
                        Padding(
                            padding: new EdgeInsets.fromLTRB(0, 5, 20, 5),
                            child: Text(
                              '状态：' + item['status_string'],
                              style: TextStyle(
                                  fontSize: 12,
                                  color: item['status_string'] == "待审核"
                                      ? Colors.red
                                      : Color.fromRGBO(120, 120, 120, 1)),
                            ))
                      ],
                    ),
                    flex: 1,
                  )
                ])),
              ),
            )));
      }
    }
    tiles.add(
      Padding(
          padding: new EdgeInsets.fromLTRB(10, 30, 10, 0),
          child: new Container(
            width: double.infinity,
            child: new Card(
              color: Color.fromRGBO(27, 182, 251, 1),
              elevation: 16.0,
              child: new FlatButton(
                child: new Padding(
                  padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                  child: new Text(
                    '继续添加检测师',
                    style: new TextStyle(color: Colors.white, fontSize: 16.0),
                  ),
                ),
                onPressed: () {
                  Navigator.pushNamed(context, 'regist');
                },
              ),
            ),
          )),
    );
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text(
            '检测师管理',
            style: TextStyle(color: Colors.black),
          ),
          backgroundColor: Colors.white,
          elevation: 0,
          // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
        ),
        body: formList.length < 1 && hasload == false
            ? Nodata()
            // new Center(
            //     child: Padding(
            //         padding: new EdgeInsets.fromLTRB(30, 0, 30, 0),
            //         child: new Container(
            //           width: double.infinity,
            //           child: new Card(
            //             color: Color.fromRGBO(27, 182, 251, 1),
            //             elevation: 16.0,
            //             child: new FlatButton(
            //               child: new Padding(
            //                 padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
            //                 child: new Text(
            //                   '无数据,添加检测师',
            //                   style: new TextStyle(
            //                       color: Colors.white, fontSize: 16.0),
            //                 ),
            //               ),
            //               onPressed: () {
            //                 Navigator.pushNamed(context, 'regist');
            //               },
            //             ),
            //           ),
            //         )),
            //   )
            : new Center(
                child: Container(
                    decoration: new BoxDecoration(
                     // color: Color.fromRGBO(238, 238, 238, 1),
                    ),
                    child:
                        // new ListView(children: <Widget>[
                        Stack(
                      children: <Widget>[
                        Align(
                            alignment: Alignment.topLeft,
                            child: Padding(
                                padding: new EdgeInsets.fromLTRB(10, 10, 10, 5),
                                child: new Container(
                                    key: _myKey,
                                    child: new Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: <Widget>[
                                          new Container(
                                            child: new TextField(
                                              onSubmitted: (value) {
                                                print(value);
                                                //if(value=="")return;
                                                setState(() {
                                                  keyword = value;
                                                  page = 1;
                                                  end = false;
                                                });
                                                print('搜索');
                                                loadData();
                                              },
                                              // controller: _phonecontroller,
                                              decoration: new InputDecoration(
                                                  border: InputBorder.none,
                                                  hintText: '搜索',
                                                  prefixIcon:
                                                      Icon(Icons.search)),
                                            ),
                                            decoration: new BoxDecoration(
                                              color: Colors.white,
                                              //设置四周圆角 角度 这里的角度应该为 父Container height 的一半
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(25.0)),
                                              //设置四周边框
                                              border: new Border.all(
                                                  width: 1,
                                                  color: Colors.white),
                                            ),
                                          ),
                                          new Container(
                                            child: filter(),
                                          )
                                        ])))),
                        Align(
                            alignment: Alignment.bottomCenter,
                            child: Padding(
                                padding: new EdgeInsets.fromLTRB(0, 150, 0, 10),
                                child: new RefreshIndicator(
                                  onRefresh: _onRefresh,
                                  child: new ListView(
                                      controller: _controller,
                                      children: <Widget>[buildcontent()]),
                                ))),
                      ],
                    )))
        //])))),
        );
  }

  Widget filter() {
    List<Widget> tiles = [];
    Widget content;

    for (var i = 0; i < items.length; i++) {
      var radios = items[i]['title'];
      bool checkvalue = false;

      //  bool has = RegExp(item['value']).hasMatch(radios);
      if (radios != "") {
        tiles.add(Padding(
            padding: new EdgeInsets.fromLTRB(10, 10, 0, 5),
            child: GestureDetector(
                // key: _myKey,
                onTap: () {
                  if (items[i]['type'] == 2) {
                    showSiteView();
                  } else
                    showfilter(items[i]['option'], i);
                },
                child: Container(
                  width: 100,
                  padding: EdgeInsets.symmetric(vertical: 8, horizontal: 10),
                  child: Center(
                      child: Text(
                    items[i]['value_des'] == ""
                        ? radios
                        : items[i]['value_des'],
                    style: new TextStyle(
                        fontSize: 10,
                        color: items[i]['select'] == false
                            ? Color.fromRGBO(120, 120, 120, 1)
                            : Colors.white),
                  )),
                  decoration: new BoxDecoration(
                    color: items[i]['select'] == false
                        ? Color.fromRGBO(225, 225, 225, 1)
                        : Colors.blue,
                    borderRadius:
                        new BorderRadius.all(new Radius.circular(10.0)),
                  ),
                ))));
      }

      // tiles.add(

    }
    content = new Container(
        child: new Wrap(
      spacing: 0,
      runSpacing: 0,
      children: tiles,
    ));

    return content;
  }

  showSiteView() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return showSite();
        });
  }

  Widget showSite() {
    return new Container(
      height: 300.0,
      child: new Column(
        children: <Widget>[
          new Padding(
            padding: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 0.0),
            child: new Container(
                height: 240.0,
                child: new ListView(children: <Widget>[siteView()])),
          ),
          new Container(
            height: 0.5,
            color: Colors.blueGrey,
          ),
          new Center(
            child: new Padding(
              padding: EdgeInsets.fromLTRB(0.0, 12.0, 0.0, 8.0),
              child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    Navigator.of(context).pop();
                    List temp = items;
                    temp[3]['value'] = "";
                    temp[3]['value_des'] = "";
                    temp[3]['select'] = false;

                    setState(() {
                      items = temp;
                      page = 1;
                    });
                    loadData();
                  },
                  child: new Text(
                    '全部',
                    style:
                        new TextStyle(fontSize: 18.0, color: Colors.blueGrey),
                  )),
            ),
          ),
        ],
      ),
    );
  }

  Widget siteView() {
    List<Widget> tiles = [];
    Widget content;
    for (var item in sites) {
      tiles.add(GestureDetector(
          onTap: () {
            // time_str = item;
            Navigator.of(context).pop();
            List temp = items;
            temp[3]['value'] = item['id'].toString();
            temp[3]['value_des'] = item['name'];
            temp[3]['select'] = true;
            setState(() {
              items = temp;
              page = 1;
            });
            loadData();
          },
          child: Container(
              height: 40, child: Center(child: new Text(item['name'])))));
    }

    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  Widget filterView(option, idx) {
    List<Widget> tiles = [];
    List<String> item = option.split(',');
    for (var i = 0; i < item.length; i++) {
      tiles.add(
        new Container(
            decoration: new BoxDecoration(
                border: Border(
                    bottom: BorderSide(width: 1, color: Color(0xffe5e5e5)))),
            height: 40,
            child: new GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () async {
                  Navigator.of(context).pop();
                  List temp = items;
                  temp[idx]['value'] = i.toString();
                  if (i == 0) {
                    temp[idx]['value_des'] = '';
                    temp[idx]['select'] = false;
                  } else {
                    temp[idx]['value_des'] = temp[idx]['title'] + ':' + item[i];
                    temp[idx]['select'] = true;
                  }
                  setState(() {
                    items = temp;
                    page = 1;
                  });
                  loadData();
                  // Navigator.pop(context);
                },
                child: Center(
                    child: Text(item[i], style: TextStyle(fontSize: 16))))),
      );
    }
    return Container(height: 123, child: new Column(children: tiles));
  }

  showfilter(option, idx) {
    // List<String> items = item["item"].split(',');
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
              child: filterView(option, idx));
        });
  }

  Future<Null> _onRefresh() async {
    await Future.delayed(Duration(seconds: 3), () {
      print('refresh');
      setState(() {
        page = 1;
      });
      loadData();
    });
  }
}
